<?php

namespace app\admin\controller\wechat;

use app\common\controller\Backend;
use app\common\model\WechatResponse;
use EasyWeChat\Foundation\Application;
use think\Exception;
use think\Db;

/**
 * 菜单管理
 *
 * @icon fa fa-list-alt
 */
class Menu extends Backend
{

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('WechatConfig');
        $this->appletLimit = $this->getAppletid();
    }

    /**
     * 查看
     */
    public function index()
    {
        $responselist = array();
        $all = WechatResponse::all();
        foreach ($all as $k => $v)
        {
            $responselist[$v['eventkey']] = $v['title'];
        }
        $where['name'] = 'menu';
        // 应用数据限制
        if ($this->appletLimit)
        {
            $where['appletid'] = $this->appletLimit;
        }
        $menu = $this->model->where($where)->find();
        if(!$menu){
            $menu = $this->model->where('name', 'menu')->where('appletid', 'default')->find();
        }


        //获取小程序的appid
        $appid = Db::table('uct_wechat_applet')->where(['appletid' => $this->appletLimit])->find()['appid'];
        $this->view->assign('responselist', $responselist);
        $this->view->assign('menu', (array) json_decode($menu['value'], TRUE));
        $this->view->assign('appid',$appid);
        $this->view->assign('minipath','pages/home/start/start');
        $this->view->assign('new_list',$this->getNews());
        return $this->view->fetch();
    }

    /**
     * 修改
     */
    public function edit($ids = NULL)
    {
        $param['menu'] = (array) json_decode($this->request->post("menu"), TRUE);
        $param['menu'] = json_encode($param['menu'], JSON_UNESCAPED_UNICODE);

        $where['name'] = 'menu';
        // 应用数据限制
        if ($this->appletLimit)
        {
            $where['appletid'] = $this->appletLimit;
        }
        $menu = $this->model->where($where)->find();
        if($menu){
            $this->model->save(['value'=>$param['menu']], ['id'=>$menu['id']]);
        }else{
            $menu = [
                'appletid' => $this->appletLimit,
                'name' => 'menu',
                'title' => '微信菜单',
                'value' => $param['menu'],
            ];
            $this->model->save($menu);
        }
        $this->success();
    }

    /**
     * 同步
     */
    public function sync($ids = NULL)
    {
        $app = new Application(\app\mpbase\service\Config::load($this->appletLimit,true));
        try
        {
            $hasError = false;
            $where['name'] = 'menu';
            // 应用数据限制
            if ($this->appletLimit)
            {
                $where['appletid'] = $this->appletLimit;
            }
            $menu = $this->model->where($where)->find();

            $menu = json_decode($menu->value, TRUE);
            foreach ($menu as $k => $v)
            {
                if (isset($v['sub_button']))
                {
                    foreach ($v['sub_button'] as $m => $n)
                    {
                        if (isset($n['key']) && !$n['key'])
                        {
                            $hasError = true;
                            break 2;
                        }
                    }
                }
                else if (isset($v['key']) && !$v['key'])
                {
                    $hasError = true;
                    break;
                }
            }
            if (!$hasError)
            {
                $ret = $app->menu->add($menu);
                if ($ret->errcode == 0)
                {
                    $this->success();
                }
                else
                {
                    $this->error($ret->errmsg);
                }
            }
            else
            {
                $this->error(__('未知参数'));
            }
        }
        catch (Exception $e)
        {
            $this->error($e->getMessage());
        }
    }


    //获取公众号内的文章素材
    public function getNews()
    {
        $app = new Application(\app\mpbase\service\Config::load($this->appletLimit,true));
        // 永久素材
        $material = $app->material;
        $news_list = $material->lists('news');
        $arr = [];
        foreach($news_list['item'] as $key => $val){
            $arr[$val['media_id']] = $val['content']['news_item'][0]['title'];
        }
        return $arr;
    }
}
